package com.github.hwangrq.myrpc.consumer.processor;

import com.github.hwangrq.myrpc.consumer.anno.RpcReference;
import com.github.hwangrq.myrpc.consumer.proxy.RpcClientProxy;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;


@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private RpcClientProxy rpcClientProxy;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    /**
     * 置处理器 --- 此处具体的实现用的是Java中的动态代理
     * 当前 bean 对象注册监控代理对象，负责增强 bean 对象方法的能力
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //1.获得Class对象
        Class<?> beanClazz = bean.getClass();
        //2.通过Class对象获取属性
        for (Field field : beanClazz.getDeclaredFields()) {
            //3.获得字段声明的注解
            if (field.getAnnotation(RpcReference.class) == null) { continue;}
            //4.创建代理对象
            Object proxy = rpcClientProxy.createProxy(field.getType());
            try {
                //5.设置属性值
                field.setAccessible(true);
                field.set(bean, proxy);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        //6.返回bean
        return bean;
    }
}
